<template>
  <AuthLayout>
    <el-card class="auth-card" shadow="never">
      <template v-slot:header>
        <div class="auth-card-header">
          <h2>用户登录</h2>
        </div>
      </template>

      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        label-position="top"
        @keyup.enter="handleLogin"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            prefix-icon="User"
            size="large"
          />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
            size="large"
          />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            @click="handleLogin"
            :loading="loading"
            size="large"
            class="auth-button"
          >
            登 录
          </el-button>
        </el-form-item>
      </el-form>

      <div class="auth-footer">
        <p>还没有账号？ <el-link type="primary" @click="$router.push('/register')" class="auth-link">立即注册</el-link></p>
      </div>

      <div v-if="errorMessage" class="auth-error">
        {{ errorMessage }}
      </div>
    </el-card>
  </AuthLayout>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { signin } from '@/services/authService'
import AuthLayout from '@/components/AuthLayout.vue'
import { User, Lock } from '@element-plus/icons-vue'
import { getCurrentUserProfile } from '@/services/userService'
import { ElMessage } from 'element-plus';

const router = useRouter()
const authStore = useAuthStore()

const loginFormRef = ref()
const loading = ref(false)
const errorMessage = ref('')

const loginForm = reactive({
  username: '',
  password: ''
})

const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少为6位', trigger: 'blur' }
  ]
}

const handleLogin = async () => {
  if (!loginFormRef.value) return
  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      errorMessage.value = ''
      try {
        const response = await signin(loginForm.username, loginForm.password)
        const { accessToken, id, username, email } = response.data

        // 1. 先设置基础认证信息
        authStore.setAuth({
          user: { id, username, email }, // 初始信息
          token: accessToken
        })

        // 2. 登录成功后，立即获取完整的用户信息 (包含权限)
        try {
            const profileResponse = await getCurrentUserProfile();
            const fullUserInfo = profileResponse.data;
            console.log('Full user info fetched after login:', fullUserInfo);

            // 3. 用包含权限的完整信息更新 Store
            // 假设后端返回的 fullUserInfo 结构类似于 { id, username, email, nickname, avatarUrl, signature, roles: [...] }
            // 其中 roles 是一个包含权限信息的数组 [{ name: 'USER', permissions: [{ name: 'POST_CREATE' }, ...] }, ...]
            authStore.setAuth({
              user: fullUserInfo, // 使用完整的用户信息
              token: accessToken // Token 保持不变
            });
        } catch (profileError) {
             console.error('Failed to fetch full user profile after login:', profileError);
             // 可以选择是否阻止登录，或者使用基础信息继续
             ElMessage.warning('获取完整用户信息失败，部分功能可能受限。');
        }

        router.push('/')
      } catch (error) {
        console.error('Login failed:', error)
        errorMessage.value = error.response?.data?.message || '登录失败，请检查用户名和密码。'
      } finally {
        loading.value = false
      }
    } else {
      console.log('Form validation failed!')
      return false
    }
  })
}
</script>

<style scoped>
.auth-card {
  border: none;
  background: transparent;
}

.auth-card-header {
  text-align: center;
  margin-bottom: 1.5rem;
  padding-bottom: 1rem;
  border-bottom: 1px solid #eee;
}

.auth-card-header h2 {
  margin: 0;
  font-size: 1.8rem;
  font-weight: 600;
  color: #ff7e5f;
  position: relative;
  display: inline-block;
}

.auth-card-header h2:after {
  content: '';
  position: absolute;
  bottom: -10px;
  left: 50%;
  transform: translateX(-50%);
  width: 40px;
  height: 3px;
  background: #ff7e5f;
  border-radius: 3px;
}

.el-form-item {
  margin-bottom: 1.8rem;
}

.auth-button {
  width: 100%;
  border-radius: 8px;
  padding: 12px 20px;
  font-weight: 600;
  letter-spacing: 1px;
  transition: all 0.3s ease;
  box-shadow: 0 4px 10px rgba(255, 126, 95, 0.3);
}

.auth-footer {
  text-align: center;
  margin-top: 1.5rem;
  font-size: 0.9rem;
  color: #666;
}

.auth-link {
  color: #ff7e5f;
  font-weight: 600;
  text-decoration: none;
  transition: all 0.2s ease;
  position: relative;
}

.auth-link:hover {
  color: #feb47b;
}

.auth-link:after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 0;
  width: 100%;
  height: 1px;
  background: #ff7e5f;
  transform: scaleX(0);
  transition: transform 0.2s ease;
}

.auth-link:hover:after {
  transform: scaleX(1);
}

.auth-error {
  margin-top: 1.5rem;
  padding: 1rem;
  background-color: rgba(255, 0, 0, 0.05);
  border: 1px solid rgba(255, 0, 0, 0.1);
  border-radius: 8px;
  color: #f56c6c;
  font-size: 0.9rem;
  text-align: center;
}

/* Element Plus Button 样式微调 */
:deep(.el-button--primary) {
  background: linear-gradient(135deg, #ff7e5f 0%, #feb47b 100%);
  border: none;
}

:deep(.el-button--primary:hover) {
  transform: translateY(-2px);
  box-shadow: 0 6px 15px rgba(255, 126, 95, 0.4);
}
</style>
